﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;

namespace Dapper.Library
{
    /// <summary>
    /// 查询集合
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class QuerySql<T> : Aggregation<T>, IQuerySql<T>
    {

        public QuerySql(IDbConnection conn, SqlProvider sqlProvider) : base(conn, sqlProvider)
        {
            TableType = typeof(T);
            SetContext = new DataBaseContext<T>
            {
                Set = this,
                OperateType = EOperateType.Query
            };
            sqlProvider.Context = SetContext;
            WhereExpressionList = new List<LambdaExpression>();
            Params = new DynamicParameters();
        }

        public QuerySql(IDbConnection conn, SqlProvider sqlProvider, IDbTransaction dbTransaction) : base(conn, sqlProvider, dbTransaction)
        {
            TableType = typeof(T);
            SetContext = new DataBaseContext<T>
            {
                Set = this,
                OperateType = EOperateType.Query
            };
            sqlProvider.Context = SetContext;
            WhereExpressionList = new List<LambdaExpression>();
            Params = new DynamicParameters();
        }

        #region 条件

        public QuerySql<T> Where(Expression<Func<T, bool>> predicate)
        {
            WhereExpressionList.Add(predicate);
            return this;
        }

        public QuerySql<T> Where<TWhere>(Expression<Func<TWhere, bool>> predicate)
        {
            WhereExpressionList.Add(predicate);
            return this;
        }

        #endregion

        /// <summary>
        /// 使用SQL执行查询语句
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public QuerySql<T> BySql(string predicate, object parameter)
        {
            SqlProvider.Context.Set.StringSql = predicate;
            SqlProvider.Context.Set.Params.AddDynamicParams(parameter);
            return this;
        }
    }
}
